var timer = window.setInterval("look()", 1000);
var countMessages = new Array();
var lastMessages = new Array();
var port = chrome.extension.connect({
    name: "MeeboConnectionPort"
});
var userIcons = new Array();


function look() {

    messages = document.getElementsByTagName("span");
    var allMessages = new Array();
    for(var i = 0,message; message = messages[i]; i++) {
        /*console.log(message.style.color);*/
        if(message.style.color == "rgb(0, 0, 0)" &&
            message.childNodes[0].style.color == "rgb(1, 99, 179)") {
            var name = message.parentNode.parentNode.parentNode.attributes["caption"].value;
            var icons = message.parentNode.parentNode.parentNode.getElementsByTagName("img");
            for (var Key in icons) {
                if(icons[Key].className == "ImBuddyIcon")
                    userIcons[name] = icons[Key].src;
            }
            lastMessages[name] = message.innerText;
            if(!countMessages[name]) {
                countMessages[name] = 0;
            }
            if(!allMessages[name]){
                allMessages[name] = 1;
            }
            else {
                allMessages[name]++;
            }
        }
    }

    for (var Key in allMessages) {
        if(countMessages[Key] < allMessages[Key]) {
            chrome.extension.sendRequest({
                "name":Key,
                "msg":lastMessages[Key],
                "icon": userIcons[Key]
            }, function(response) {});
            countMessages[Key] = allMessages[Key];
        }
    }
}

//Ausführung eines Click Events als bsp ! sollte uns eigtl helfen

port.postMessage({
    category : "Settings"
});
port.onMessage.addListener(function(msg) {
    if (msg.category == "Settings") {
        for (var Key in msg.obj) {
            if(document.getElementById(Key))
                document.getElementById(Key).value = msg.obj[Key];
        }
        if(msg.obj["csstags"] != "") {
            var myStyle = "<"+"style type=\"text\/css\">";
            myStyle += msg.obj["csstags"];
            myStyle += "<\/style>";
            var head = document.getElementsByTagName("head")[0];
            head.insertAdjacentHTML("beforeEnd",myStyle);
        }
    }

});
document.getElementById("network").value = "icq";
document.getElementById("login").value = "595490866";
document.getElementById("password").value = "36enn1ch7";
if(document.getElementById("signon")){
    var sign = document.getElementById("signon");
    var evt=document.createEvent("MouseEvents");
    if(evt && evt.initMouseEvent)evt.initMouseEvent("click",true,true,document.defaultView,1,0,0,0,0,false,false,false,false,0,null);
    sign.dispatchEvent(evt); //dispatchEvent(event);
}
